package com.longge.websocket.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.longge.websocket.endpoint.MyWebSocketHandler;
import com.longge.websocket.interceptor.WebSocketInterceptor;

@Configuration
@EnableWebSocket
public class MySocketConfiguration implements WebSocketConfigurer {
	@Autowired
	private WebSocketInterceptor webSocketInterceptor;
	@Autowired
	private MyWebSocketHandler myWebSocketHandler;

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(myWebSocketHandler, "/ws/2")
        .addInterceptors(webSocketInterceptor).setAllowedOrigins("*");
	}

	/**
	 * 使用 websockt注解的时候，使用@EnableScheduling注解
	 * 启动的时候一直报错，增加这个bean 则报错解决。
	 * 报错信息：  Unexpected use of scheduler.
	 *https://stackoverflow.com/questions/49343692/websocketconfigurer-and-scheduled-are-not-work-well-in-an-application
	 *
	 * @return
	 */
	@Bean
	public TaskScheduler taskScheduler(){
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(10);
		taskScheduler.initialize();
		return taskScheduler;
	}
}
